//
//  YUHomeTopReusableView.swift
//  tuniu
//
//  Created by 于世民 on 2019/8/16.
//  Copyright © 2019 于世民. All rights reserved.
//

import UIKit
import RxSwift
import RxCocoa
import TYCyclePagerView
import Kingfisher

class YUHomeTopReusableView: UICollectionReusableView {
    
    var picArr = Variable<[String]>([])
    
    private let pagerView = TYCyclePagerView().then {
        $0.isInfiniteLoop = true;
        $0.autoScrollInterval = 3.0;
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        initUI()
        bindUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

extension YUHomeTopReusableView {

    private func initUI() {
        
        // 轮播图
        self.addSubview(pagerView)
        
        pagerView.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
        }
        

        pagerView.register(YUScrollBarCell.self, forCellWithReuseIdentifier: "YUScrollBarCell")
        pagerView.delegate = self
        pagerView.dataSource = self
    }
    
    func bindUI() {
        // 刷新轮播图
        picArr.asObservable().subscribe { (_) in
            self.pagerView.reloadData()
            }.disposed(by: rx.disposeBag)
    }
}

extension YUHomeTopReusableView: TYCyclePagerViewDataSource, TYCyclePagerViewDelegate {
    
    func numberOfItems(in pageView: TYCyclePagerView) -> Int {
        return picArr.value.count
    }
    
    func layout(for pageView: TYCyclePagerView) -> TYCyclePagerViewLayout {
        
        let layout = TYCyclePagerViewLayout()
        layout.itemSize = CGSize(width: pagerView.frame.width, height: pagerView.frame.height)
        layout.itemSpacing = 0
        layout.itemHorizontalCenter = true
        
        return layout
    }
    
    func pagerView(_ pagerView: TYCyclePagerView, cellForItemAt index: Int) -> UICollectionViewCell {
        let cell = pagerView.dequeueReusableCell(withReuseIdentifier: "YUScrollBarCell", for: index) as! YUScrollBarCell
        cell.imageView.kf.setImage(with: URL(string: picArr.value[index]))
        return cell
    }

}
